<?php
    require('init.php');

    if(!isset($_SESSION['commande']) || !$_SESSION['commande'] instanceof Commande) {
        Tools::redirect('panier.php');
    }

    $req = 'cmd=_notify-validate';
    foreach ($_POST as $key => $value) {
      $value = urlencode(stripslashes($value));
      $req .= "&$key=$value";
    }

    $header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
    $header .= "Host: www.sandbox.paypal.com:443\r\n";
    $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
    $fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);
    // ERREUR HTTP
    if (!$fp) {
        echo "%NIP-F-SOCKOPEN, HTTP error " . $errno . " " . $errstr;
        exit;
    }
    else {
        $payment_status = $_POST['payment_status'];  // Si Completed : tout est OK
        $payment_amount = $_POST['mc_gross'];       // montant payé
        $txn_id = $_POST['txn_id'];                 // id Paypal de la transaction
        $receiver_email = $_POST['receiver_email']; // mail du vendeur
        $payer_email = $_POST['payer_email'];       // mail de l'acheteur
        $first_name = $_POST['first_name'];         // prénom de l'acheteur
        $last_name = $_POST['last_name'];           // nom de l'acheteur
        $idUnique = $_POST['custom'];               // notre id unique de transaction
        $pending_reason = $_POST['pending_reason']; // raison si paiement en attente
        $payment_currency = $_POST['mc_currency'];  // devise du paiement
        fputs ($fp, $header . $req);
        $bon = false;
        while (!feof($fp)) {
            $res = fgets ($fp, 1024);
            if (strcmp ($res, "VERIFIED") == 0) {
                $bon = true;
            }
        }
        fclose ($fp);
        if(!$bon) {
            Tools::redirect('paiement.php');
        }
        else {
            $statut = Statut::rechercheStatut(1);
            $_SESSION['commande']->addCommandeHistorique($statut);
            unset($_SESSION['commande']);
            Tools::redirect('index.php');
        }
    }
?>
